﻿using RAP.Framework.Libary.Configuration;
using RAP.Framework.Libary.DataSource.Model.DataSource;
using RAP.Framework.Libary.Utils;
using System;

namespace RAP.Web.Libary.Config
{
  /// <summary>
  /// 站点参数对象
  /// </summary>
  public abstract class SiteSettingsBase
  {
    /// <summary>
    /// 
    /// </summary>
    public static object LockObject { get; } = new object();

    #region 静态属性
    /// <summary>
    /// 判断当前是否处于调试状态
    /// </summary>
    public static bool IsDebug { get; set; }

    /// <summary>
    /// 是否在控制台显示日志
    /// </summary>
    public static bool ShowLogs { get; set; }

    /// <summary>
    /// 数据源Id前缀
    /// </summary>
    public static string DataSourceKeyPrefix { get; set; }

    /// <summary>
    /// 数据源配置根节点名称：DataConfig
    /// </summary>
    public static string DataConfigField { get; set; } = "DataConfig";

    /// <summary>
    /// 数据源配置集合节点名称：DataSources
    /// </summary>
    public static string DataSourcesField { get; set; } = "DataSources";

    /// <summary>
    /// 
    /// </summary>
    public static DataSourceConfig DataSourceConfig { get; private set; }

    /// <summary>
    /// 数据库连接字符串解密密码的配置节点名称
    /// </summary>
    public static string DataSourceConnectionPasswordKey { get; set; }
    #endregion 静态属性

    /// <summary>
    /// 加载站点配置参数
    /// </summary>
    public static void LoadSettings(IConfigurationManager configuration, Type siteSettingsType)
    {
      var appSettings = configuration;
      Action loadSettings = () =>
      {
        //从配置文件读取参数，对SiteSettings的静态字段赋值
        foreach (string key in appSettings.Keys)
        {
          try
          {
            siteSettingsType.SetStaticMemberValue(key, appSettings[key]);
          }
          catch (Exception e)
          {
            throw new Exception("站点参数初始化发生异常！Key：" + key, e);
          }
        }
        DataSourceConfig = new DataSourceConfig(appSettings.ToDictionary(DataConfigField));
      };
      appSettings.OnSettingsChangedEvent += new EventHandler((sender, args) =>
     {
       //当配置发生变化时，刷新站点参数的配置
       loadSettings();
     });
      loadSettings();//加载站点参数
      Extentions.STRING_TRANSLATOR_DEFAULT_PARAMS = appSettings;
    }
  }
}
